# coding=utf8
# self import statement allows access to the karamba functions
# simply vCard parser, 
# currently only handle, names, mails and phones

###############################################################################
#													 		  
#	Copyright 2007 Pavel Nemec					
#																
#	This program is free software; you can redistribute it and/or modify	 
#	it under the terms of the GNU Lesser General Public License as published 
#	by the Free Software Foundation; either version 2 of the License, or	 
#	(at your option) any later version.									  
#																			
#	This program is distributed in the hope that it will be useful,		  
#	but WITHOUT ANY WARRANTY; without even the implied warranty of		   
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the			
#	GNU Lesser General Public License for more details.					  
#																			 
#	You should have received a copy of the GNU Lesser General Public License 
#	along with this program; if not, write to the Free Software			  
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA 
#																			 
###############################################################################	
# author: Pavel Nemec <pnemec@suse.cz>
# 2007-06-29 HACK WEEK
import karamba
import os
import sys
import readvcard
import string
import userConfigs

mailCommand=["kmail" ,"-s New message for you"]
kopeteListCommand=["dcop --pipe","kopete" ,"KopeteIface", "onlineContacts"]
##kopeteInvokeCommand=[ nothnink for now]
clipBoardCommand=["dcop", "klipper" ,"klipper" ,"setClipboardContents"]
phoneCommand="echo " #no command for now
kabCommand=["kaddressbook"]

margin=10 #argin in theme picture
userImageSize=32
textAreaPositionX=20
textAreaPositionY=50
maxAppletHeight=240
minAppletHeight=75
appletWidth=210
numberOfItems=8
cfgPosX=195
cfgPosY=minAppletHeight-15
cfgPoMaxY=150
inputBoxXPos=margin+userImageSize+10
inputBoxYPos=margin
inputBoxLength=appletWidth - (inputBoxXPos + margin + userImageSize)
fontSize=12
fontSizeBig=15
footerHeight=18
textLinePosition=appletWidth-(textAreaPositionX + margin +10) #position of line in main applet body


global background
global mousex
global mousey
global mainClass

def initWidget(widget):
	global mainClass
	mainClass = KadressBookGui(widget)

	

def meterClicked(widget, meter, button):
	global mainClass
	mainClass.mouseEvent(meter,button)
	
	
def widgetUpdated(widget):
	pass

def widgetClicked(widget, x, y, button):
	pass

def widgetMouseMoved(widget, x, y, button):
	global mousex, mousey
	mousex=x
	mousey=y
	mainClass.mouseOver(x,y,)

def keyPressed(widget, meter, char):
	mainClass.keyboradEvent(meter,char)		

# program i called, return me somethink
def commandOutput(widget, pid, output):
	pass;
		


class KadressBookGui:
	
	#searchInputBox
	def __init__(self,widget):
		self.w=widget
		self.config = userConfigs.Config(widget)
		self.searcher = readvcard.ReadVcard()
		self.config.storeVCardReader(self.searcher)
		
	
		self.initTextAreas()   
		self.__initVariables()

		#
		# add all files stored by karamba facility
		tmpfiles=karamba.readConfigEntry(self.w,"files")				
		if tmpfiles==None:
			print "no files stored"
		else:
			self.files=tmpfiles.split()
			for i in self.files:
				self.searcher.addFile(i)
		
		
		self.NAME=0
		self.PHONE=1
		self.MAIL=2
		self.IM=3
		
		
		
	def __initVariables(self):
		self.idstack=[]
		tmpY=textAreaPositionY+10
		for i in range(numberOfItems):
			item=range(5)
			item[0]="" #string
			itembg = karamba.createImage(self.w,textAreaPositionX+10,tmpY, self.config.getImage("list_full.png"))
			karamba.hideImage(self.w,itembg);
			karamba.attachClickArea(self.w,itembg,"")
			item[1]=itembg #clickable background
			itemtext= karamba.createText(self.w,textAreaPositionX+15,tmpY,appletWidth-(textAreaPositionX + margin +10),fontSize+3,"")
			karamba.hideText(self.w,itemtext)
			item[2]=itemtext#text Object
			item[3]=-1 #id
			item[4]=None #custom data
			self.idstack.append(item)
			tmpY+=20
			
		self.customImages=[] #images generated during search they are karamba image !
		self.bigAreaTexts=[]
		self.foundItems=[] #this is what serach return, I need to remember it because of back button
		self.itemsPerPage=10
		self.positionInStack=0
		self.view="small"
		self.fakeUserPicture = karamba.createImage(self.w,margin,margin,self.config.getImage("kuser.png"))
		self.searchInputBox = karamba.createInputBox(self.w, inputBoxXPos, margin, inputBoxLength, 23, "")
		karamba.changeInputBoxFrameColor(self.w,self.searchInputBox,72,139,141)
		self.searchPicture = karamba.createImage(self.w,inputBoxXPos+inputBoxLength+5,inputBoxYPos,self.config.getImage("search.png"))
		karamba.hideImage(self.w,self.searchPicture)
		karamba.attachClickArea(self.w,self.searchPicture)
		self.background = karamba.createBackgroundImage(self.w, 0, 0, self.config.getImage("background_small.png"))
		print "adding files ", self.config.getImage("footer.png")
		
		self.footer = karamba.createImage(self.w, 0, minAppletHeight-footerHeight, self.config.getImage("footer.png"))
		self.footerText=karamba.createText(self.w,appletWidth/2, minAppletHeight-footerHeight,60,215,"")
		karamba.changeTextColor(self.w,self.footerText,255,255,255)
		self.footerRightArrow = karamba.createImage(self.w,(appletWidth/2)+10,minAppletHeight-footerHeight,self.config.getImage("rightarrow.png"))
		self.footerLeftArrow  = karamba.createImage(self.w,(appletWidth/2)-10,minAppletHeight-footerHeight,self.config.getImage("leftarrow.png"))
		
		karamba.attachClickArea(self.w,self.footerLeftArrow)
		karamba.attachClickArea(self.w,self.footerRightArrow)	
		self.needle=-1
		

		self.files=[] #files with vCal files
		
		#self.configure view
		self.cfg = range(3)
		self.cfg[0]=karamba.createImage(self.w,cfgPosX,cfgPosY,self.config.getImage("circle.png"))
		self.cfg[1]=karamba.createImage(self.w,cfgPosX,cfgPosY,self.config.getImage("circle_bold.png"))
		karamba.attachClickArea(self.w,self.cfg[1],"")
		karamba.attachClickArea(self.w,self.cfg[0],"")
		karamba.hideImage(self.w,self.cfg[1])
		
		
		# first parse and init footer position
		self.searcher.parseAllFiles()
		size=str(self.searcher.getItemCount())
		karamba.changeText(self.w,self.footerText,str(size+" of "+size))
		
		textlen=karamba.getTextSize(self.w,self.footerText)[0]
#		print "len ", textlen
		lx=appletWidth/2-((textlen/2) +20)
		rx=appletWidth/2+textlen/2 +10
		y=karamba.getImagePos(self.w,self.footerRightArrow)[1]
		
#		print "r: ",rx," l:", lx
		karamba.moveImage(self.w,self.footerRightArrow,rx,y)
		karamba.moveImage(self.w,self.footerLeftArrow,lx,y)
		karamba.moveText(self.w,self.footerText,appletWidth/2-textlen/2,y)
		
		self.showFooter(False )		
		
		
	def __moveArrows(self): 
		''' arrows are static :( move only center text!
		'''
		textlen = karamba.getTextSize(self.w,self.footerText)[0]
		x=appletWidth/2- textlen/2  +5
		y=karamba.getTextPos(self.w,self.footerText)[1]
		karamba.moveText(self.w,self.footerText,x,y)
		#print "moveArrows l: ",+x," r:",x, " textlen is: ",textlen
		
	def keyboradEvent(self, component,key):
		#fix concept bug
		if self.view=="cfg":
			#self.switchTextAreaN("small")
			print "ignoring keys in cfg view"
			return
		if len(key)==0: print "it is 0"
		text=""
		if component == self.searchInputBox:
			text = karamba.getInputBoxValue(self.w, self.searchInputBox)
				
		else:
			#focus is not on input box, but who care ! ;)
			text = karamba.getInputBoxValue(self.w, self.searchInputBox)
			text=text+key
			karamba.changeInputBox(self.w, self.searchInputBox,text)
			#karamba.setInputFocus(self.w,self.searchInputBox) #just for sure causing trouble
			
		if len(text) >0:
			if len(key)==0:
				# detection of arrow or enter should be her
				print "non ASCI key" 
			else:
				if self.view != "big": self.switchTextAreaN("big")
				self.searchForText(text)
		else:
			self.switchTextAreaN("small")
		
		pass;
		
	def mouseEvent (self, component, button):
		#print "have mouse event: ",component
		if self.view !="contacts":
			for i in range(len(self.idstack)):
				item=self.idstack[i] #0 string, 1 bg, 2 texta
				
				itembg=item[1]
				if itembg == component:
							self.searchContact(item[3])
		else:
			 for i in range(len(self.idstack)):
				item=self.idstack[i] #0 string, 1 bg, 2 texta 3 id
				itembg=item[1]
				id=item[3]
				if itembg == component:					
					if id==self.NAME:
						self.executeCommand(clipBoardCommand,item[0])
					if id==self.MAIL:
						self.executeCommand(clipBoardCommand,item[0])
					if id==self.PHONE:
						self.executeCommand(clipBoardCommand,item[0])
					if id==self.IM:
						self.executeCommand(clipBoardCommand,item[0])
				if item[4]!=None and item[4]==component:
					#print "have an picture on item"
					if id==self.NAME :
						self.callName(item[0])
						self.config.mail_enable
					if id==self.MAIL and self.config.mail_enable=="yes":
						self.writeMail(item[0])
					if id==self.PHONE:
						self.callPhone(item[0])
					if id==self.IM and self.config.im_enable=="yes":
						self.callIM(item[0])
		if component==self.cfg[1]:
#			print "have and cfg event, view is: ",self.view
			if self.view=="cfg":
				self.config.hide()
				self.switchTextAreaN("small")
				 # quite hack here, 
				 # only here I know that cfg view was activated and now it is canceled 
				karamba.moveImage(self.w,self.cfg[0],cfgPosX,cfgPosY)
				karamba.moveImage(self.w,self.cfg[1],cfgPosX,cfgPosY)
			else:
				self.switchTextAreaN("cfg")
				karamba.moveImage(self.w,self.cfg[0],cfgPosX,maxAppletHeight-15)
				karamba.moveImage(self.w,self.cfg[1],cfgPosX,maxAppletHeight-15)
		if component == self.searchPicture:
			if self.view=="contacts":
				self.switchTextAreaN("big")
				self.fillItems(self.foundItems)
			elif self.view=="big":
				karamba.changeInputBox(self.w,self.searchInputBox,"")
				self.switchTextAreaN("small")
			
		if self.view=="cfg":
			#delegate clickable
			self.config.mouseEvent(component)
		if component ==self.footerLeftArrow or component==self.footerRightArrow:
#			print "set and needle"
			if component== self.footerLeftArrow:
#				print "left arrow clicked"
				self.needle-=1
				if(self.needle<=-1):
					self.needle=self.searcher.getItemCount()-1	
				
			if component== self.footerRightArrow:
#				print "right arrow clicked"
				self.needle+=1
				if(self.needle>=self.searcher.getItemCount()-1):
					self.needle=0
			
			tmptext=str(self.needle) +" of "+str(self.searcher.getItemCount())
#			print "setting to needle: ", tmptext
			karamba.changeText(self.w,self.footerText,tmptext)
			self.fillContact(self.needle)
			
	def initTextAreas(self):
		#self.textArea = karamba.createImage(self.w,textAreaPositionX+40,textAreaPositionY-15,"images/textarea_background.png")
		self.infoText = karamba.createText(self.w,inputBoxXPos,margin+28,120,20,"Welcome to kabSA")
		self.bigTextArea = karamba.createImage(self.w,textAreaPositionX+10,textAreaPositionY, self.config.getImage("textareaBig_background.png"))
		karamba.hideImage(self.w, self.bigTextArea)

	def switchTextAreaN(self,kind):
		self.view=kind
		self.switchTextArea()
	def switchTextArea(self):
#		print "self view is: ",self.view
		self.cleanBigTextArea()
		if self.view == "small":
			karamba.hideImage(self.w, self.bigTextArea)
			karamba.showInputBox(self.w,self.searchInputBox)
			karamba.showText(self.w, self.infoText)
			karamba.showText(self.w, self.infoText)
			karamba.deleteImage(self.w,self.background)
			self.background = karamba.createBackgroundImage(self.w, 0, 0,  self.config.getImage("background_small.png"))
			karamba.setImagePath(self.w,self.searchPicture,self.config.getImage("search.png"))
			karamba.hideImage(self.w,self.searchPicture)	
			karamba.resizeWidget(self.w,appletWidth,minAppletHeight)
			karamba.showImage(self.w,self.cfg[0])
			karamba.showImage(self.w, self.fakeUserPicture)			
			self.moveFooter(0,minAppletHeight-footerHeight)
			self.showFooter(False)
			return 
		if self.view== "big" or self.view=="contacts":
			#karamba.hideImage(self.w, self.textArea)
			karamba.showImage(self.w, self.bigTextArea)
			karamba.hideText(self.w, self.infoText)
			karamba.deleteImage(self.w,self.background)
			karamba.hideImage(self.w,self.cfg[0])
			#karamba.moveImage(self.w,self.footer,0,maxAppletHeight-18)
	
			self.background = karamba.createBackgroundImage(self.w, 0, 0,  self.config.getImage("background_big.png"))
			karamba.resizeWidget(self.w,appletWidth,maxAppletHeight)
			self.moveFooter(0,maxAppletHeight-footerHeight)
			if self.view == "contacts":
				karamba.setImagePath(self.w,self.searchPicture,self.config.getImage("back.png"))
			if self.view == "big": 
				karamba.setImagePath(self.w,self.searchPicture,self.config.getImage("erase.png"))
			karamba.showImage(self.w,self.searchPicture)
			self.showFooter(True)
			return 
			
		if self.view=="cfg":
			karamba.hideInputBox(self.w,self.searchInputBox)
			karamba.hideImage(self.w,self.searchPicture)
			#karamba.hideImage(self.w, self.textArea)
			karamba.hideImage(self.w,self.fakeUserPicture)
			karamba.hideText(self.w, self.infoText)
			karamba.deleteImage(self.w,self.background)
			self.background = karamba.createBackgroundImage(self.w, 0, 0,  self.config.getImage("background_big.png"))
			karamba.resizeWidget(self.w,appletWidth,maxAppletHeight)
			self.showFooter(False)
			self.config.show()
			return 
			karamba.showInputBox(self.w,self.searchInputBox)
			karamba.showImage(self.w,self.searchPicture)
			self.config.hide()
			self.showFooter(True)
			# not needed as i fix it in keyEvent method
			karamba.moveImage(self.w,self.cfg[0],cfgPosX,cfgPosY)
			karamba.moveImage(self.w,self.cfg[1],cfgPosX,cfgPosY)
	def moveFooter(self,x,y):
#		print "moving footer to ",y
		karamba.moveImage(self.w,self.footer,x,y)
		#do not move arrows in X-axe, self is done elsewhere 
		karamba.moveImage(self.w,self.footerRightArrow,karamba.getImagePos(self.w,self.footerRightArrow)[0],y)
		karamba.moveImage(self.w,self.footerLeftArrow, karamba.getImagePos(self.w,self.footerLeftArrow)[0],y)
		karamba.moveText(self.w,self.footerText,karamba.getTextPos(self.w,self.footerText)[0],y)
	def showFooter(self,visible):	
		if(visible==False):
			karamba.hideImage(self.w,self.footer)
			karamba.hideImage(self.w,self.footerLeftArrow)
			karamba.hideImage(self.w,self.footerRightArrow)
			karamba.hideText(self.w,self.footerText)
		else:
			karamba.showImage(self.w,self.footer)
			karamba.showImage(self.w,self.footerLeftArrow)
			karamba.showImage(self.w,self.footerRightArrow)
			karamba.showText(self.w,self.footerText)
		
	def cleanBigTextArea(self):
#		print "cleaning"
		for i in self.idstack:
			string=i[0]
			image=i[1]
			text=i[2]
			karamba.hideImage(self.w,image)
			karamba.hideText(self.w,text)
			karamba.changeText(self.w,text,"")
			karamba.changeTextSize(self.w,text,fontSize)
			if i[4]!=None:
				karamba.hideImage(self.w,i[4])
		for i in self.customImages:
			karamba.deleteImage(self.w,i)
		self.customImages=[]
	def searchForText(self, text):
		found = self.searcher.search(text)
#		print "i have found ", len(found), " items"
		if self.view=="small": self.switchTextAreaN("big")
		else: self.cleanBigTextArea()
		
		if len(found)>0:
			self.fillItems(found)
		
	def fillContact(self, contactID):
		if self.view!="contacts": self.switchTextAreaN("contacts")
		self.cleanBigTextArea()
		contact=self.searcher.getContact(contactID)
		if contact==None:
			print "kab.fillContact: cannot get Contact for id: ",contactID
			return
		
		karamba.changeText(self.w,self.footerText,str(contactID)+" of "+ str(self.searcher.getItemCount()))
		self.needle=contactID
		self.__moveArrows()
		name=contact.jmeno
		phones = contact.phoneList
		mails=contact.mailList
		ims=contact.imList #instant messangers
		index=0
		#name
		idItem = self.idstack[index]
		index+=1
		idItem[0]=name
		idItem[3]=self.NAME
		#print "filling contact ",name, " with phones ",len(phones), ", mails ",len(mails), " and ims: ",len(ims)
		karamba.showImage(self.w,idItem[1]) #show image
		karamba.changeTextSize(self.w,idItem[2],fontSizeBig)
		karamba.addImageTooltip(self.w,idItem[1],"Open Kaddressbook, midle click to copy names into search field")
		karamba.changeText(self.w,idItem[2],"  " + idItem[0]) #change text from item
		karamba.showText(self.w,idItem[2]) #show text
		
		
#		karamba.changeInputBox(self.w,self.searchInputBox,name)
		#karamba.changeInputBoxSelection(self.w,self.searchInputBox,0,5)
		
##		max 5 phones
		for i in range(0,min(4,len(phones))):
			#print "writing phone on position ",i
			phone=phones[i]
			idItem = self.idstack[index]
			index+=1
			idItem[0]=phone[1]
			idItem[3]=self.PHONE
			karamba.showImage(self.w,idItem[1]) #show image
			karamba.addImageTooltip(self.w,idItem[1],"Copy phone number to clipboard")
			karamba.changeText(self.w,idItem[2],idItem[0]) #change text from item
			karamba.showText(self.w,idItem[2]) #show text
			position=karamba.getImagePos(self.w,idItem[1])
			idItem[4]=karamba.createImage(self.w,textAreaPositionX-10,position[1],self.config.getImage("phone.png"))
			karamba.attachClickArea(self.w,idItem[4],"")
			
		
		for i in range(0,min(4,len(mails))):
			#print "writing mail on position ",i
			mail=mails[i]
			idItem = self.idstack[index]
			index+=1
			idItem[0]=mail[1]
			idItem[3]=self.MAIL
			karamba.showImage(self.w,idItem[1]) #show image
			karamba.addImageTooltip(self.w,idItem[1],"Copy adress to clipboard and create new mail")
			karamba.changeText(self.w,idItem[2],idItem[0]) #change text from item
			karamba.showText(self.w,idItem[2]) #show text	
			position=karamba.getImagePos(self.w,idItem[1])
			idItem[4]=karamba.createImage(self.w,textAreaPositionX-10,position[1],self.config.getImage("mail.png"))
			karamba.attachClickArea(self.w,idItem[4],"")
		for i in range(0,min(4,len(ims))):
			#print "writing im on position ",i
			im=ims[i]
			idItem = self.idstack[index]
			index+=1
			idItem[0]=im[1]
			idItem[3]=self.IM
			karamba.showImage(self.w,idItem[1]) #show image
			karamba.addImageTooltip(self.w,idItem[1],"Copy IM name to clipboard")
			karamba.changeText(self.w,idItem[2],idItem[0]) #change text from item
			karamba.showText(self.w,idItem[2]) #show text	
			position=karamba.getImagePos(self.w,idItem[1])
			idItem[4]=karamba.createImage(self.w,textAreaPositionX-10,position[1],self.config.getImage("im.png"))
			karamba.attachClickArea(self.w,idItem[4],"")
	#there is bug here, i am throwing OUT all items which do not fit into numberOfItems !!
	def fillItems(self, items):
		self.foundItems=items
#		print "should fill ", (len(items)), "items"
		for i in range(min(numberOfItems,len(items))):
			idItem = self.idstack[i]
			item=items[i]
			idItem[0]=item[1] #pass the text
			idItem[3]=item[0] #pass the id
			idItem[4]=None
			#print "filling item ", i
		self.__fillItems()
		
	def __fillItems(self):
		#''' fill items from self.idstack which has to be allready filled '''
		for i in range(min(len(self.foundItems),len(self.idstack))):
			idItem = self.idstack[i]
			karamba.showImage(self.w,idItem[1]) #show image
			karamba.changeText(self.w,idItem[2],idItem[0]) #change text from item
			karamba.showText(self.w,idItem[2]) #show text
			if idItem[4]!=None:
				karamba.showImage(self.w,idItem[4])
	def searchContact(self, id):
		contact = self.searcher.getContact(id)
		if contact == None:
			print "return null"
		else:
			self.fillContact(id)
	
	def callPhone(self, phone):
		print "going to handle phone number: ",phone
	def callIM(self, im):
		print "going to handle IM: ",im
		print "should call some dcop...later"
	def callName(self, name):
		#is adressbook running? or not? just do not care and call it
		karamba.executeInteractive(self.w,kabCommand)
	def writeMail(self, adress):
		print "going to write email to adress: ",adress
		self.executeCommand(mailCommand,adress)
	def executeCommand(self,command,variable):
		mycommand=command
		mycommand.append(variable)
		karamba.executeInteractive(self.w,mycommand)
		mycommand.pop()
	def mouseOver(self,x, y):
		if self.view=="small":
			#cfg
##			print "mouse over"
			if abs(x-cfgPosX)<7 and abs(y-cfgPosY)<7:
				karamba.hideImage(self.w,self.cfg[0])
				karamba.showImage(self.w,self.cfg[1])
				self.cfg[2]=1
			elif self.cfg[2]==1:
				self.cfg[2]=0
				karamba.hideImage(self.w,self.cfg[1])
				karamba.showImage(self.w,self.cfg[0])
				
		
#	def parseFiles(self):
#		'''
#			reparse newly added files, remove duplicite (todo), and correct position of arrows
#		'''
#		self.searcher.parseNewFiles()
#		size=len(str(self.searcher.getItemCount()))  #how many contacts we have, messured in character length
#		
#		print "pased, size is: ", size
#		# we need to count messurement for footer
	

	  
	def setTheme(self,name):  
		pass
		 #karamba.writeself.configEntry(self.w,"theme",theme)
		
 
		
		
